package com.jader.activities;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jader.adapter.CommentAdapter;
import com.jader.beans.LunTan_ALLHuiFu;
import com.jader.beans.LunTan_gujia_Bens;
import com.jader.main.MainActivity;
import com.jader.util.JaderApplication;
import com.jader.util.NoScrollListView;
import com.jader.util.TiShi;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.zlp.jader.R;

public class GuJiaDetail extends Activity implements OnClickListener {
	LunTan_gujia_Bens all_Bens;
	ImageView userNameHeardImageView,// 頭像
			huifuImageView,// 回復
			fenxiangImageView;// 分享
	ImageView zanshiImageView1, zanshiImageView2, zanshiImageView3;

	private EditText commentEdit; // 评论输入框
	Button suoyou_detail_fasong;
	TextView userNameTextView,// 發帖人姓名
			fatietimeTextView,// 發帖時間
			fatiebiaotiTextView,// 发帖标题
			fatieneirongtTextView,// 發帖內容
			//zanTextView,

			fanhuiluntan;// 返回论坛
	BitmapUtils bitmapUtils;
	ImageView zan, shoucang;
	NoScrollListView commentList;// 评论数据列表
	boolean scfalg;// 是否被收藏
	boolean dzfalg;// 是否被点赞
	String[] images;
	LinearLayout layout;
	private boolean isReply; // 是否是回复
	private String comment = "";
	// 记录对话框中的内容
	private CommentAdapter adapter;
	private List<LunTan_ALLHuiFu> list = new ArrayList<LunTan_ALLHuiFu>(),
			allHuiFus;
	private String url = JaderApplication.getIP();
	private String url1 = JaderApplication.getIP() + "/Jader/SerCollect";
	private String url2 = JaderApplication.getIP() + "/Jader/DianZanServlet";
	private String getHuifu_url = JaderApplication.getIP() + "/Jader/client";
	private LunTan_ALLHuiFu pinlun, huifu_pinglun;
	private String huifu_url = JaderApplication.getIP() + "/Jader/client";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
		setContentView(R.layout.activity_gu_jia_detail);
		bitmapUtils = JaderApplication.getBitmapUtils();
		Intent intent = this.getIntent();
		all_Bens = (LunTan_gujia_Bens) intent.getSerializableExtra("position");
		initView();
		initData();
	}

	private void initData() {
		RequestParams params = new RequestParams();
		params.addBodyParameter("type", JaderApplication.TIEZI_HUIFU + "");
		params.addBodyParameter("tieziid", "" + all_Bens.getTieziId());
		pinlun = new LunTan_ALLHuiFu(null, all_Bens.getTieziId(), 0,
				all_Bens.getTieziId(), null, null, null, 1);
		getHuiFu(getHuifu_url, params);
	}

	/**
	 * 显示或隐藏输入法
	 */
	private void onFocusChange(boolean hasFocus) {
		final boolean isFocus = hasFocus;
		(new Handler()).postDelayed(new Runnable() {
			public void run() {
				InputMethodManager imm = (InputMethodManager) commentEdit
						.getContext().getSystemService(INPUT_METHOD_SERVICE);
				if (isFocus) {
					// 显示输入法
					imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
				} else {
					// 隐藏输入法
					imm.hideSoftInputFromWindow(commentEdit.getWindowToken(), 0);
				}
			}
		}, 100);
	}

	/**
	 * 判断对话框中是否输入内容
	 */
	private boolean isEditEmply() {
		comment = commentEdit.getText().toString().trim();
		if (comment.equals("")) {
			Toast.makeText(getApplicationContext(), "评论不能为空",
					Toast.LENGTH_SHORT).show();
			return false;
		}
		commentEdit.setText("");
		return true;
	}

	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == 10) {
				isReply = true;
				huifu_pinglun = new LunTan_ALLHuiFu();
				pinlun = (LunTan_ALLHuiFu) msg.obj;
				onFocusChange(true);
			}
		}
	};
	 TextView pingluntexTextView;
	private List<String> list_url;

	private void initView() {
		commentList = (NoScrollListView) findViewById(R.id.gujia_detai_pinglun_list);
		View head = View
				.inflate(GuJiaDetail.this, R.layout.gujia_pinglun, null);
		commentList.addHeaderView(head);
		all_Bens = (LunTan_gujia_Bens) getIntent().getSerializableExtra(
				"position");
		layout=(LinearLayout) findViewById(R.id.linearLayout2);
		fanhuiluntan = (TextView) findViewById(R.id.fanhuigujia);
		userNameHeardImageView = (ImageView) findViewById(R.id.item_luntan_gujia_detail_imageview);
		zan = (ImageView) findViewById(R.id.gujia_detail_zan);
		fenxiangImageView = (ImageView) findViewById(R.id.gujia_detail_fenxiang);
		shoucang = (ImageView) findViewById(R.id.gujia_detail_shoucang);
		huifuImageView = (ImageView) findViewById(R.id.gujia_detail_pinglun);

		huifuImageView.setOnClickListener(this);

		zanshiImageView1 = (ImageView) findViewById(R.id.item_luntan_gujia_detail_zhanshiimageview);
		zanshiImageView2 = (ImageView) findViewById(R.id.item_luntan_gujia_detail_zhanshiimageview1);
		zanshiImageView3 = (ImageView) findViewById(R.id.item_luntan_gujia_detail_zhanshiimageview2);

		userNameTextView = (TextView) findViewById(R.id.item_luntan_gujia_detail_nameText);
		fatietimeTextView = (TextView) findViewById(R.id.item_luntan_gujia_detail_timeText);
		fatiebiaotiTextView = (TextView) findViewById(R.id.item_luntan_gujia_detail_biaotiText);
		fatieneirongtTextView = (TextView) findViewById(R.id.item_luntan_gujia_detail_neirong);
		//zanTextView = (TextView) findViewById(R.id.gujia_detail_zan_Number_Text);
		pingluntexTextView = (TextView) findViewById(R.id.gujia_detail_pinglun_Number_Text);

		commentList = (NoScrollListView) findViewById(R.id.gujia_detai_pinglun_list);
		commentEdit = (EditText) findViewById(R.id.gujia_detail_shuru);
		suoyou_detail_fasong = (Button) findViewById(R.id.gujia_detail_fasong);

		suoyou_detail_fasong.setOnClickListener(this);
		zan.setOnClickListener(this);
		shoucang.setOnClickListener(this);
		fenxiangImageView.setOnClickListener(this);
		bitmapUtils.display(userNameHeardImageView, JaderApplication.getIP()+"/Jader"+all_Bens.getUserBens()
				.getPicture());

		list_url = all_Bens.getList();

		if (list_url == null || list_url.size() == 0) {
		}

		if (list_url != null && list_url.size() == 1) {
			bitmapUtils.display(zanshiImageView1, url + list_url.get(0));
		}
		if (list_url != null && list_url.size() == 2) {
			bitmapUtils.display(zanshiImageView1, url + list_url.get(0));
			bitmapUtils.display(zanshiImageView2, url + list_url.get(1));
		}

		if (list_url != null && list_url.size() > 2) {
			bitmapUtils.display(zanshiImageView1, url + list_url.get(0));
			bitmapUtils.display(zanshiImageView2, url + list_url.get(1));
			bitmapUtils.display(zanshiImageView3, url + list_url.get(2));
		}

		fanhuiluntan.setOnClickListener(this);
		userNameTextView.setText(all_Bens.getUserBens().getUsername());
		fatietimeTextView.setText(all_Bens.getDate());
		fatiebiaotiTextView.setText(all_Bens.getTheme());
		fatieneirongtTextView.setText(all_Bens.getContent());
		//zanTextView.setText(all_Bens.getPraiseNumber() + "");
		zanshiImageView1.setOnClickListener(this);
		zanshiImageView2.setOnClickListener(this);
		zanshiImageView3.setOnClickListener(this);
		huifuImageView.setOnClickListener(this);
		getwebcheckdianzan(url1);
		getwebcheckshoucang(url1);
		getwebcheckdianzan(url2);

		//判断list里面有没有数据
				if (list_url.size() != 0) {
					// 当图片路径不为0时，传给数组
					images = new String[list_url.size()];
					
					for (int i = 0; i < list_url.size(); i++) {
						images[i] = JaderApplication.getIP()+list_url.get(i);
					}
					Log.e("lujinglujing", images[0]);
					if (images[0].equals(JaderApplication.getIP()+"/Jader/image/tiezi/20151103200032472.png")) {
						layout.setVisibility(View.GONE);
						zanshiImageView1.setVisibility(View.GONE);
						zanshiImageView2.setVisibility(View.GONE);
						zanshiImageView3.setVisibility(View.GONE);
					}
				}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		// 返回论坛
		case R.id.fanhuigujia:
			Intent intent = new Intent(GuJiaDetail.this, MainActivity.class);
			intent.putExtra("tiaozhuan", 3);
			startActivity(intent);
			break;
		// 收藏
		case R.id.gujia_detail_shoucang:
			if (scfalg) {

				getwebshoucang(url1);
				shoucang.setImageResource(R.drawable.shoucang1);

				scfalg = false;
			} else {
				getwebquxiao(url1);
				shoucang.setImageResource(R.drawable.shoucang);

				scfalg = true;
			}

			break;
		// 点赞
		case R.id.gujia_detail_zan:

			if (dzfalg) {

				zan.setImageResource(R.drawable.zan1);

				getwebdianzan(url2);
				dzfalg = false;
			} else {
				zan.setImageResource(R.drawable.zan);
				getwebzanquxiao(url2);
				dzfalg = true;
			}
			break;
		// 分享
		case R.id.gujia_detail_fenxiang:
			JaderApplication.startShareApp(GuJiaDetail.this, "分享到",
					all_Bens.getTheme(), all_Bens.getContent());

			break;
		// 评论
		case R.id.gujia_detail_fasong:
			if (JaderApplication.user == null) {
				JaderApplication.login(GuJiaDetail.this);
			} else {
				if (isEditEmply()) { // 判断用户是否输入内容

					onFocusChange(false);
					// 日期
					SimpleDateFormat format = new SimpleDateFormat(
							"yyyy-MM-dd HH:mm");
					Date time = new Date(System.currentTimeMillis());
					String date = format.format(time);
					SimpleDateFormat format1 = new SimpleDateFormat(
							"yyyyMMddHHmmsssss");
					Date time1 = new Date(System.currentTimeMillis());
					long tiezi_id = Long.parseLong(format1.format(time1));
					huifu_pinglun = new LunTan_ALLHuiFu(JaderApplication.user,
							tiezi_id, pinlun.getTiezi_id(),
							pinlun.getParent_id(), date, "", comment, 0);
					RequestParams params = new RequestParams();
					params.addBodyParameter("type",
							JaderApplication.INSERT_TIEZI_HUIFU + "");
					params.addBodyParameter("huifu",
							new Gson().toJson(huifu_pinglun));
					huifu(huifu_url, params, isReply);
				}
			}
			break;
		case R.id.item_luntan_gujia_detail_zhanshiimageview:
			Log.e("path", list_url.size() + "'");
			tiaoimage();
			break;
		case R.id.item_luntan_gujia_detail_zhanshiimageview1:
			tiaoimage();
			break;
		case R.id.item_luntan_gujia_detail_zhanshiimageview2:
			tiaoimage();
			break;
		case R.id.deatile_pinglun:
			onFocusChange(true);
			break;
		default:
			break;
		}
	}

	private void tiaoimage() {
		// 定义一个数组，存放图片路径

		if (list_url.size() != 0) {
			Intent intent = new Intent(this, ImagePagerActivity.class);
			// 图片url,一般从数据库中或网络中获取
			intent.putExtra("images", images);
			this.startActivity(intent);
		}
	}

	// 判断帖子是否收藏过
	private void getwebcheckshoucang(final String url1) {

		HttpUtils httpUtils1 = new HttpUtils();
		RequestParams params = new RequestParams();
		params.addBodyParameter("flg", "2");
		if (JaderApplication.user == null) {
			shoucang.setImageResource(R.drawable.shoucang);
		} else{
		params.addBodyParameter("userid", JaderApplication.user.getUserid() + "");
		params.addBodyParameter("postid", all_Bens.getTieziId() + "");
		httpUtils1.send(HttpMethod.POST, url1, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						// TODO Auto-generated method stub
						String result = responseInfo.result;
						if (result.equals("是")) {
							scfalg = false;
							shoucang.setImageResource(R.drawable.shoucang1);
						} else {
							scfalg = true;
						}

					}

					@Override
					public void onFailure(HttpException error, String msg) {
						// TODO Auto-generated method stub
					}
				});}

	}

	// 取消收藏
	private void getwebquxiao(String url1) {
		HttpUtils httpUtils1 = new HttpUtils();
		RequestParams params = new RequestParams();
		params.addBodyParameter("flg", "3");
		if (JaderApplication.user == null) {
			shoucang.setImageResource(R.drawable.shoucang);
			JaderApplication.login(this);
		} else{
		params.addBodyParameter("userid", JaderApplication.user.getUserid() + "");
		params.addBodyParameter("postid", all_Bens.getTieziId() + "");
		httpUtils1.send(HttpMethod.POST, url1, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {

						TiShi.quxiaoshoucang(GuJiaDetail.this);
					}

					@Override
					public void onFailure(HttpException error, String msg) {

					}
				});}
	}

	// 收藏
	private void getwebshoucang(String url1) {
		HttpUtils httpUtils1 = new HttpUtils();
		RequestParams params = new RequestParams();
		params.addBodyParameter("flg", "1");
		if (JaderApplication.user == null) {
			shoucang.setImageResource(R.drawable.shoucang);
			JaderApplication.login(this);
		} else{
		params.addBodyParameter("userid", JaderApplication.user.getUserid() + "");
		params.addBodyParameter("postid", all_Bens.getTieziId() + "");
		httpUtils1.send(HttpMethod.POST, url1, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						// TODO Auto-generated method stub
						TiShi.shoucang(GuJiaDetail.this);
						// String result = responseInfo.result;
						// Myappliction.show(PostBeanActivity.this, result);
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						// TODO Auto-generated method stub
					}
				});}

	}

	// 判断帖子是否点赞
	private void getwebcheckdianzan(final String url2) {

		HttpUtils httpUtils1 = new HttpUtils();
		RequestParams params = new RequestParams();
		params.addBodyParameter("flg", "2");
		if (JaderApplication.user == null) {
			shoucang.setImageResource(R.drawable.shoucang);
		} else{
		params.addBodyParameter("userid", JaderApplication.user.getUserid() + "");
		params.addBodyParameter("postid", all_Bens.getTieziId() + "");
		httpUtils1.send(HttpMethod.POST, url2, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						String result = responseInfo.result;
						if (result.equals("是")) {
							dzfalg = false;
							zan.setImageResource(R.drawable.zan1);
						} else {
							dzfalg = true;
						}

					}

					@Override
					public void onFailure(HttpException error, String msg) {
						// TODO Auto-generated method stub
					}
				});}

	}

	// 取消点赞
	private void getwebzanquxiao(String url2) {
		HttpUtils httpUtils1 = new HttpUtils();
		RequestParams params = new RequestParams();
		params.addBodyParameter("flg", "3");
		if (JaderApplication.user == null) {
			shoucang.setImageResource(R.drawable.shoucang);
			JaderApplication.login(this);
		} else{
		params.addBodyParameter("userid", JaderApplication.user.getUserid() + "");
		params.addBodyParameter("postid", all_Bens.getTieziId() + "");
		httpUtils1.send(HttpMethod.POST, url2, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						int a = all_Bens.getPraiseNumber() - 1;
						all_Bens.setPraiseNumber(a);
						//zanTextView.setText(a + "");
						TiShi.quxiaodianzan(GuJiaDetail.this);
					}

					@Override
					public void onFailure(HttpException error, String msg) {

					}
				});}
	}

	// 点赞
	private void getwebdianzan(String url2) {
		HttpUtils httpUtils1 = new HttpUtils();
		RequestParams params = new RequestParams();
		params.addBodyParameter("flg", "1");
		if (JaderApplication.user == null) {
			shoucang.setImageResource(R.drawable.shoucang);
			JaderApplication.login(this);
		} else{
		params.addBodyParameter("userid", JaderApplication.user.getUserid() + "");
		params.addBodyParameter("postid", all_Bens.getTieziId() + "");
		httpUtils1.send(HttpMethod.POST, url2, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						// TODO Auto-generated method stub
						TiShi.dianzan(GuJiaDetail.this);
						int a = all_Bens.getPraiseNumber() + 1;
						all_Bens.setPraiseNumber(a);
						//zanTextView.setText(a + "");
						// String result = responseInfo.result;
						// Myappliction.show(PostBeanActivity.this, result);
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						// TODO Auto-generated method stub
					}
				});}

	}

	private void getHuiFu(String url, RequestParams params) {
		JaderApplication.httpUtils.send(HttpMethod.POST, url, params,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						String result = arg0.result;
						allHuiFus = new ArrayList<LunTan_ALLHuiFu>();
						Type type = new TypeToken<List<LunTan_ALLHuiFu>>() {
						}.getType();
						allHuiFus = JaderApplication.gson
								.fromJson(result, type);
						for (LunTan_ALLHuiFu lunTan_ALLHuiFu : allHuiFus) {
							if (all_Bens.getTieziId() == lunTan_ALLHuiFu
									.getHuifu_id()) {
								Log.e("tiezih", lunTan_ALLHuiFu.toString());
								list.add(lunTan_ALLHuiFu);
							}
						}
						adapter = new CommentAdapter(GuJiaDetail.this, list,
								allHuiFus, R.layout.comment_item, handler);
						commentList.setAdapter(adapter);
						adapter.notifyDataSetChanged();
					}

				});

	}

	private void huifu(String url, RequestParams params, final boolean isReplay) {
		JaderApplication.httpUtils.send(HttpMethod.POST, url, params,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						JaderApplication.show(GuJiaDetail.this, "无网络连接");

					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						String result = arg0.result;
						if ("true".equals(result)) {
							if (!isReply) {
								list.add(huifu_pinglun);
							} else {
								adapter.add(huifu_pinglun);
							}
							adapter.notifyDataSetChanged();
						} else {
							JaderApplication
									.show(GuJiaDetail.this, "回复失败，请重试！");
						}

					}
				});
		this.isReply = false;
	}

}
